#!usr/bin/env python
#coding=utf8

import os
import time,datetime
import uuid
from PIL import Image

from django.http import HttpResponse
from django.utils import simplejson
from django.db import transaction

from tuangou import config
from tuangou.common_logic.template import render_to_response
from tuangou.common_logic import commutil
from tuangou.business_logic import bi_item, bi_category, bi_tuangou, bi_supply, bi_hotitem, bi_appform, bi_systemkeyvalue, bi_cooperation
from forms import ItemForm, CooperationPlatformForm, CooperationBrandForm

def index(request):
    '''
    管理首页
    '''
    r_dict = {}
    return render_to_response('admin/master.html', r_dict, request)

def product_index(request):
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
    
    order_by='-createdtime'    
    items = bi_item.get_item_list(page, page_size, order_by)
    item_count = bi_item.get_item_count()
    r_dict = {'items': items, 'order_by':order_by, 'total_count':item_count, 'page':page, 'page_size':page_size }

    return render_to_response('admin/product_index.html', r_dict, request)

def product_add_view(request):
    categorys = bi_category.get_category_list()
    supplys = bi_supply.get_supplier_list()
    r_dict = {'categorys':categorys, 'supplys':supplys}
    return render_to_response('admin/product_add.html', r_dict, request)

@transaction.commit_on_success
def product_add_save_json(request):
    '''
    添加商品信息
    '''
    form = ItemForm(request.POST)
    if form.is_valid() and request.method == "POST" and request.FILES and len(request.FILES) > 0:
        #try:
        item = bi_item.save_item(**form.cleaned_data)
        bi_item.add_item_categorys(item, request.POST.get('hid_category_ids', ''))
        bi_item.add_item_supplys(item, request.POST.get('hid_supply_ids', ''))
        thumburl, originalurl = commutil.save_item_image(request.FILES['file'])
        #保存图片和商品关联
        bi_item.save_item_image(item.id, thumburl, originalurl, "home")
        transaction.commit()
        #跳转到修改界面
        return product_edit_view(request, item.id)
        #except Exception, e:
            #print str(e)
            #transaction.rollback()

    return product_index(request)

def product_edit_view(request, product_id):
    item = bi_item.get_item_by_id(product_id)
    images = item.itemimage_set.all()
    for img in images:
        if img.imagetype=='home':
            img.ishome = True
        else:
            img.ishome = False
            
    categories = item.itemcategory_set.all()
    categoriesIds = ""
    for c in categories:
        categoriesIds = categoriesIds + str(c.id) + ','
    if len(categoriesIds) > 0:
        categoriesIds = categoriesIds[0 : len(categoriesIds) - 1]
        
    supplys = item.supplier_set.all()
    supplysIds = ""
    for d in supplys:
        supplysIds = supplysIds + str(d.id) + ','
    if len(supplysIds) > 0:
        supplysIds = supplysIds[0 : len(supplysIds) - 1]
    
    r_dict = {'item':item, 'images':images, 'categorys':bi_category.get_category_list(), 'categoriesIds':categoriesIds, 'supplys':bi_supply.get_supplier_list(), 'supplysIds':supplysIds}
    
    return render_to_response('admin/product_edit.html', r_dict, request)

@transaction.commit_on_success
def product_edit_save_json(request, product_id):
    '''
    修改商品信息
    '''
    form = ItemForm(request.POST)
    if form.is_valid() and request.method == "POST" :
        try:
            item = bi_item.update_item(product_id, **form.cleaned_data)
            bi_item.add_item_categorys(item, request.POST.get('hid_category_ids', ''))
            bi_item.add_item_supplys(item, request.POST.get('hid_supply_ids', ''))
            homeimageid = int(request.POST.get('imagetype', 0))
            if item.homeimage.id != homeimageid:
                for img in item.itemimage_set.all():
                    if img.id == homeimageid:
                        img.imagetype = "home"
                    else:
                        img.imagetype = "minor"
                    img.save()
            
            transaction.commit()
        except Exception, e:
            print str(e)
            transaction.rollback()

    #跳转到修改界面
    return product_edit_view(request, product_id)

@transaction.commit_on_success
def product_edit_save_file(request, product_id):
    ''' 新增图片 '''
    if product_id and request.method == "POST" and request.FILES and len(request.FILES) > 0:
        try:
            for i in range(1, 6):
                file = request.FILES.get("file" + str(i), None)
                if file:
                    thumburl, originalurl = commutil.save_item_image(file)
                    #保存图片和商品关联
                    bi_item.save_item_image(product_id, thumburl, originalurl, "minor")
                
            transaction.commit()
        except Exception, e:
            print str(e)
            transaction.rollback()

    return product_edit_view(request, product_id)

@transaction.commit_on_success
def product_delete_item_file(request, image_id):
    r_dict = {'success': False}
    try:
        bi_item.del_item_image_by_id(image_id)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
    
    return HttpResponse(simplejson.dumps(r_dict))
        
@transaction.commit_on_success
def product_delete_json(request, product_id):
    '''
    删除商品
    '''
    r_dict = {'success': False}
    try:
        bi_item.del_item_by_id(product_id)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
    
    return HttpResponse(simplejson.dumps(r_dict))
    
def category_index(request):
    categorys = bi_category.get_category_list()
    r_dict = {'categorys':categorys}
    return render_to_response('admin/category_index.html', r_dict, request)

def category_add_view(request):
    categorys = bi_category.get_top_category_list()
    hasTopCategory = len(categorys) > 0
    r_dict = {'categorys':categorys, 'hasTopCategory':hasTopCategory}
    return render_to_response('admin/category_add.html', r_dict, request)

@transaction.commit_on_success
def category_add_json(request):
    r_dict = {'success': False}
    try:
        data = {'title':request.POST['title'], 'index':int(request.POST['index']), 'parent_id':int(request.POST['parent_id']), 'level':int(request.POST['level'])}
        bi_category.add_category(data)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
    
    return HttpResponse(simplejson.dumps(r_dict))

def category_edit_view(request, category_id):
    category = bi_category.get_category_by_id(category_id)
    if category:
        hasTopCategory = category.level > 1
        parent = []
        if hasTopCategory:
            parent = bi_category.get_top_category_list()
            for p in parent:
                if p == category.parent:
                    p.selected = True
        r_dict = {'parent':parent, 'category':category, 'hasTopCategory':hasTopCategory}
        return render_to_response('admin/category_edit.html', r_dict, request)
    
    return index(request)

@transaction.commit_on_success
def category_edit_json(request, category_id):
    r_dict = {'success': False}
    try:
        data = {'title':request.POST['title'], 'index':int(request.POST['index']), 'parent_id':int(request.POST['parent_id']), 'level':int(request.POST['level'])}
        bi_category.save_category(category_id, data)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
    
    return HttpResponse(simplejson.dumps(r_dict))

@transaction.commit_on_success
def category_delete_json(request, category_id):
    r_dict = {'success': False}
    try:
        bi_category.delete_category(category_id)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
    
    return HttpResponse(simplejson.dumps(r_dict))

def supply_index(request):
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
     
    supplys = bi_supply.get_supply_list_by_page(page, page_size)
    supply_count = bi_supply.get_supply_count()
    r_dict = {'supplys': supplys, 'total_count':supply_count, 'page':page, 'page_size':page_size }

    return render_to_response('admin/supply_index.html', r_dict, request)

def supply_add_view(request, supply_id):
    '''supply_id等于0是新增，否则是修改'''
    r_dict = {'supply_id':supply_id}
    if supply_id>0:
        supply = bi_supply.get_supply_by_id(supply_id)
        r_dict = {'supply':supply,'supply_id':supply_id}
    return render_to_response('admin/supply_add.html', r_dict, request)

@transaction.commit_on_success
def supply_add_save_json(request, supply_id):
    title = request.POST.get("title", None)
    supply_id= int(supply_id)
    if title:
        try:
            if supply_id>0:
                bi_supply.save_supply(supply_id, title)
            else:
                bi_supply.add_supply(title)
            transaction.commit()
        except Exception, e:
            transaction.rollback()

    return supply_index(request)

@transaction.commit_on_success
def supply_delete_json(request, supply_id):
    r_dict = {'success': False}
    try:
        bi_supply.delete_supply(supply_id)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
    
    return HttpResponse(simplejson.dumps(r_dict))

#团购管理view
def tuangou_index(request, product_id):
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
     
    item = bi_item.get_item_by_id(product_id)
    if item:
        page, page_size, offset = commutil.get_page_offset(page, page_size)
        tuangous = item.tuangouinfo_set.all()[offset : offset + page_size]
        for t in tuangous:
            try:
                t.supply = t.supplier
            except Exception:
                t.supply = None
            t.tuan_price = commutil.decimalFormat(t.tuan_price)
        tuangou_count = item.tuangouinfo_set.count()
        r_dict = {'item':item, 'tuangous': tuangous, 'total_count':tuangou_count, 'page':page, 'page_size':page_size }
        return render_to_response('admin/tuangou_index.html', r_dict, request)
    
@transaction.commit_on_success
def tuangou_delete_json(request, tuangou_id):
    r_dict = {'success': False}
    try:
        bi_tuangou.delete_tuangou_by_id(tuangou_id)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
    
    return HttpResponse(simplejson.dumps(r_dict))

def tuangou_add_view(request, product_id, tuangou_id):
    product_id = int(product_id)
    tuangou_id = int(tuangou_id)
    supplys = bi_supply.get_supplier_list()
    if tuangou_id>0:
        tuangou = bi_tuangou.get_itemtuangou_by_id(tuangou_id)
        d = time.strptime(str(tuangou.tuan_saledate), '%Y-%m-%d %H:%M:%S')
        print d
        tuangou.tuan_saledate = '%s-%s-%s'%(d[0], d[1], d[2])
        item = tuangou.item
        try:
            supplier = tuangou.supplier
            for s in supplys:
                if s.id == supplier.id:
                    s.selected = True
        except Exception:
            supplier = None
    else:
        item = bi_item.get_item_by_id(product_id)
        tuangou = None
    r_dict = {'supplys':supplys, 'item':item, 'tuangou': tuangou, 'product_id':product_id, 'tuangou_id':tuangou_id}
    return render_to_response('admin/tuangou_add.html', r_dict, request)

@transaction.commit_on_success
def tuangou_add_save_json(request, tuangou_id):
    r_dict = {'success': False}
    if request.method == "POST" :
        tuangou_id = int(tuangou_id)
        data = {'tuan_salecount':request.POST['tuan_salecount'], 'tuan_url':request.POST['tuan_url'], 'supplier_id':request.POST['supplier_id'], 'tuan_price':request.POST['tuan_price'], 'tuan_sitename':request.POST['tuan_sitename'], 'item_id':request.POST['item_id'], 'tuan_saledate':request.POST['tuan_saledate'], 'tuan_context':request.POST['tuan_context']};
        try:
            if tuangou_id > 0:
                bi_tuangou.update_tuangou(tuangou_id, data)
            else:
                bi_tuangou.save_tuangou(data)
            r_dict['success'] = True
            transaction.commit()
        except Exception, e:
            transaction.rollback()
            if hasattr(e, 'messages'):
                r_dict['err_msg'] = ', '.join(e.messages)
            else:
                r_dict['err_msg'] = str(e)
        
    return HttpResponse(simplejson.dumps(r_dict))


#hot商品管理
def hotproduct_index(request):
    hots = bi_hotitem.get_hotitem_list()
    r_dict = {'hots':hots}
    return render_to_response('admin/left_product_index.html', r_dict, request)

def hotproduct_edit_view(request, id):
    hot = bi_hotitem.get_hotitem_by_id(id)
    r_dict = {'hot':hot}
    return render_to_response('admin/left_product_edit.html', r_dict, request)

@transaction.commit_on_success
def hotproduct_edit_save_json(request, id):
    r_dict = {'success': False}
    id = int(id)
    index = request.POST.get("index", None)
    try:
        if id > 0 and index:
            bi_hotitem.save_hotitem(id, index)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
        
    return HttpResponse(simplejson.dumps(r_dict))

@transaction.commit_on_success
def hotproduct_delete_json(request, id):
    r_dict = {'success': False}
    id = int(id)
    try:
        if id > 0:
            bi_hotitem.delete_hotitem(id)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
        
    return HttpResponse(simplejson.dumps(r_dict))

def hotproduct_select_view(request):
    keyword = request.GET.get('keyword',None)
    items = []
    if keyword:
        items = bi_hotitem.search_item_list(keyword)
    r_dict = {'items':items}        
    return render_to_response('admin/left_product_add.html', r_dict, request)

@transaction.commit_on_success
def hotproduct_add_json(request, product_id):
    r_dict = {'success': False}
    product_id = int(product_id)
    try:
        if product_id > 0:
            bi_hotitem.add_hotitem(0, product_id)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
        
    return HttpResponse(simplejson.dumps(r_dict))


def feedback_index(request):
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
     
    feedbacks = bi_appform.get_feedback_list_by_page(page, page_size)
    feedback_count = bi_appform.get_feedback_count()
    r_dict = {'feedbacks': feedbacks, 'total_count':feedback_count, 'page':page, 'page_size':page_size }

    return render_to_response('admin/feedback_index.html', r_dict, request)

@transaction.commit_on_success
def feedback_delete_json(request, feedback_id):
    r_dict = {'success': False}
    feedback_id = int(feedback_id)
    try:
        if feedback_id > 0:
            bi_appform.del_feedback_by_id(feedback_id)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
        
    return HttpResponse(simplejson.dumps(r_dict))

def appform_index(request):
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
     
    appforms = bi_appform.get_appform_list_by_page(page, page_size)
    appform_count = bi_appform.get_appform_count()
    r_dict = {'appforms': appforms, 'total_count':appform_count, 'page':page, 'page_size':page_size }

    return render_to_response('admin/appform_index.html', r_dict, request)

@transaction.commit_on_success
def appform_delete_json(request, appform_id):
    r_dict = {'success': False}
    appform_id = int(appform_id)
    try:
        if appform_id > 0:
            bi_appform.del_appform_by_id(appform_id)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
        
    return HttpResponse(simplejson.dumps(r_dict))

def supply_product_index(request, supply_id):
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
    
    order_by='-createdtime'
    items, item_count = bi_supply.get_item_list(supply_id, page, page_size, order_by)
    r_dict = {'items': items, 'order_by':order_by, 'total_count':item_count, 'page':page, 'page_size':page_size }

    return render_to_response('admin/supply_product_index.html', r_dict, request)

def about_edit(request):
    key = 'about_us'
    if request.method == "POST":
        r_dict = {'success': False}
        try:
            bi_systemkeyvalue.update_by_key(key, request.POST.get("value", ""))
            r_dict['success'] = True
        except Exception, e:
            if hasattr(e, 'messages'):
                r_dict['err_msg'] = ', '.join(e.messages)
            else:
                r_dict['err_msg'] = str(e)
        return HttpResponse(simplejson.dumps(r_dict))
    else:        
        keyvalue = bi_systemkeyvalue.get_by_key(key)
        r_dict = {'value':keyvalue.value}
        return render_to_response('admin/about_edit.html', r_dict, request)

def joinus_edit(request):
    key = 'join_us'
    if request.method == "POST":
        r_dict = {'success': False}
        try:
            bi_systemkeyvalue.update_by_key(key, request.POST.get("value", ""))
            r_dict['success'] = True
        except Exception, e:
            if hasattr(e, 'messages'):
                r_dict['err_msg'] = ', '.join(e.messages)
            else:
                r_dict['err_msg'] = str(e)
        return HttpResponse(simplejson.dumps(r_dict))
    else:        
        keyvalue = bi_systemkeyvalue.get_by_key(key)
        r_dict = {'value':keyvalue.value}
        return render_to_response('admin/joinus_edit.html', r_dict, request)


def contactus_edit(request):
    key = 'contact_us'
    if request.method == "POST":
        r_dict = {'success': False}
        try:
            bi_systemkeyvalue.update_by_key(key, request.POST.get("value", ""))
            r_dict['success'] = True
        except Exception, e:
            if hasattr(e, 'messages'):
                r_dict['err_msg'] = ', '.join(e.messages)
            else:
                r_dict['err_msg'] = str(e)
        return HttpResponse(simplejson.dumps(r_dict))
    else:        
        keyvalue = bi_systemkeyvalue.get_by_key(key)
        r_dict = {'value':keyvalue.value}
        return render_to_response('admin/contactus_edit.html', r_dict, request)


def companyimg_edit(request):
    key = 'company_publicity_pictures'
    r_dict = {'value':''}
    if request.method == "POST" and request.FILES and len(request.FILES) > 0:
        file = request.FILES.get("file", None)
        p, ext = os.path.splitext(file.name)
        savePath = os.path.join(config.STATIC_PATH, 'productimgs')
        fileName = 'company_publicity_pictures' + ext      
        image = Image.open(file)
        image.thumbnail((1200,400),Image.ANTIALIAS)
        image.save(os.path.join(savePath, fileName))
        
        bi_systemkeyvalue.update_by_key(key, fileName)
        r_dict['value'] = fileName
    elif request.method == "GET":
        keyvalue = bi_systemkeyvalue.get_by_key(key)
        r_dict['value'] = keyvalue.value
        
    return render_to_response('admin/company_publicity_pictures_edit.html', r_dict, request)


def cooperationplatform_index(request):
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
    
    order_by='index'    
    platforms = bi_cooperation.get_platform_list(page, page_size, order_by)
    platform_count = bi_cooperation.get_platform_count()
    r_dict = {'platforms': platforms, 'order_by':order_by, 'total_count':platform_count, 'page':page, 'page_size':page_size }

    return render_to_response('admin/cooperation_platform_index.html', r_dict, request)

def cooperationplatform_add(request):
    if id :
        try:
            if request.method == "POST" :
                form = CooperationPlatformForm(request.POST)
                if form.is_valid():
                    platform = bi_cooperation.save_platform(**form.cleaned_data)
                    
                    if request.FILES and len(request.FILES) > 0:
                        file = request.FILES.get("file", None)
                        if file:
                            p, ext = os.path.splitext(file.name)
                            savePath = os.path.join(config.STATIC_PATH, 'productimgs')
                            fileName = str(uuid.uuid1()) + ext
                            image = Image.open(file)
                            image.thumbnail((130,60),Image.ANTIALIAS)
                            image.save(os.path.join(savePath, fileName))
                            platform.imgurl = fileName
                            platform.update()
                        
                return cooperationplatform_index(request)
            else:
                return render_to_response('admin/cooperation_platform_add.html', None, request)
        except Exception, e:
            print str(e)

def cooperationplatform_edit(request, id):
    if id :
        try:
            if request.method == "POST" :
                form = CooperationPlatformForm(request.POST)
                if form.is_valid():
                    platform = bi_cooperation.update_platform(id, **form.cleaned_data)
                    
                    if request.FILES and len(request.FILES) > 0:
                        file = request.FILES.get("file", None)
                        if file:
                            p, ext = os.path.splitext(file.name)
                            savePath = os.path.join(config.STATIC_PATH, 'productimgs')
                            fileName = str(uuid.uuid1()) + ext
                            image = Image.open(file)
                            image.thumbnail((130,60),Image.ANTIALIAS)
                            image.save(os.path.join(savePath, fileName))
                            if platform.imgurl != "" > 0:
                                path = os.path.join(config.STATIC_PATH, 'productimgs', platform.imgurl)
                                if os.path.isfile(path):
                                    os.remove(path)
                            platform.imgurl = fileName
                            platform.update()
                        
                return cooperationplatform_index(request)
            else:
                platform = bi_cooperation.get_platform_by_id(id)
                r_dict = {'platform':platform}
                return render_to_response('admin/cooperation_platform_edit.html', r_dict, request)
                
        except Exception, e:
            print str(e)

def cooperationplatform_delete_json(request, id):
    r_dict = {'success': False}
    try:
        bi_cooperation.delete_platform(id)
        r_dict['success'] = True
        transaction.commit()
    except Exception, e:
        transaction.rollback()
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
    
    return HttpResponse(simplejson.dumps(r_dict))


def cooperationbrand_index(request):
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
    
    order_by='index'    
    brands = bi_cooperation.get_brand_list(page, page_size, order_by)
    brand_count = bi_cooperation.get_brand_count()
    r_dict = {'brands': brands, 'order_by':order_by, 'total_count':brand_count, 'page':page, 'page_size':page_size }
    print brands
    print brand_count
    return render_to_response('admin/cooperation_brand_index.html', r_dict, request)

def cooperationbrand_add(request):
    if id :
        try:
            if request.method == "POST" :
                form = CooperationBrandForm(request.POST)
                if form.is_valid():
                    brand = bi_cooperation.save_brand(**form.cleaned_data)
                    
                    if request.FILES and len(request.FILES) > 0:
                        file = request.FILES.get("file", None)
                        if file:
                            p, ext = os.path.splitext(file.name)
                            savePath = os.path.join(config.STATIC_PATH, 'productimgs')
                            fileName = str(uuid.uuid1()) + ext
                            image = Image.open(file)
                            image.thumbnail((130,60),Image.ANTIALIAS)
                            image.save(os.path.join(savePath, fileName))
                            brand.imgurl = fileName
                            brand.update()
                        
                return cooperationbrand_index(request)
            else:
                return render_to_response('admin/cooperation_brand_add.html', None, request)
        except Exception, e:
            print str(e)

def cooperationbrand_edit(request, id):
    if id :
        try:
            if request.method == "POST" :
                form = CooperationBrandForm(request.POST)
                if form.is_valid():
                    brand = bi_cooperation.update_brand(id, **form.cleaned_data)
                    
                    if request.FILES and len(request.FILES) > 0:
                        file = request.FILES.get("file", None)
                        if file:
                            p, ext = os.path.splitext(file.name)
                            savePath = os.path.join(config.STATIC_PATH, 'productimgs')
                            fileName = str(uuid.uuid1()) + ext
                            image = Image.open(file)
                            image.thumbnail((130,60),Image.ANTIALIAS)
                            image.save(os.path.join(savePath, fileName))
                            if brand.imgurl != "" > 0:
                                path = os.path.join(config.STATIC_PATH, 'productimgs', brand.imgurl)
                                if os.path.isfile(path):
                                    os.remove(path)
                            brand.imgurl = fileName
                            brand.update()
                        
                return cooperationbrand_index(request)
            else:
                brand = bi_cooperation.get_brand_by_id(id)
                r_dict = {'brand':brand}
                return render_to_response('admin/cooperation_brand_edit.html', r_dict, request)
                
        except Exception, e:
            print str(e)

def cooperationbrand_delete_json(request, id):
    r_dict = {'success': False}
    try:
        bi_cooperation.delete_brand(id)
        r_dict['success'] = True
    except Exception, e:
        if hasattr(e, 'messages'):
            r_dict['err_msg'] = ', '.join(e.messages)
        else:
            r_dict['err_msg'] = str(e)
    
    return HttpResponse(simplejson.dumps(r_dict))















